package com.neo.push.server.mongo;

import com.alibaba.fastjson.JSON;
import com.neo.push.core.AcceptPush;
import com.neo.push.core.PushText;
import com.neo.push.core.PushType;
import com.neo.push.server.connection.HashedWheelMessageTimer;
import com.neo.push.server.message.MessageMapper;
import com.neo.push.server.message.PushMessageFactory;
import com.neo.push.server.message.PushMessageMonitor;
import com.neo.push.server.message.PushMessageState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collections;
import java.util.List;

/**
 * Created by lock on 17-7-31.
 */
public class MongoPushMessageMonitor extends HashedWheelMessageTimer implements PushMessageMonitor {

    private MessageMapper messageMapper = new MongoMessageMapper();
    private Logger logger = LoggerFactory.getLogger(MongoPushMessageMonitor.class);

    /**
     * 表示某一个消息没收到
     * @param messageId
     * @throws Exception
     */
    @Override
    public void handleMessageTimeout(String messageId) throws Exception {
        messageMapper.updateMessageState(messageId, PushMessageState.TIMEOUT);
    }


    @Override
    public void messageSend(AcceptPush safetyMessage) {
        messageMapper.savePushMessage(safetyMessage);
    }

    @Override
    public void receipt(String messageId) {
        AcceptPush text = messageMapper.loadPushMessage(messageId);
        messageMapper.updateMessageState(messageId,PushMessageState.RECEIVED);
        if(null!=text&&text.getPushType() == PushType.BUCKET){
            logger.info(" received message :"+text.toString());
            List<PushText> pushTexts = JSON.parseArray(text.getContent(),PushText.class);
            for(PushText t : pushTexts){
                receipt(t.getMessageId());
            }
        }
    }


    @Override
    public List<AcceptPush> loadOfflineMessage(String receiver){
        List<AcceptPush> pushTexts = messageMapper.loadReceiverOffline(receiver);
        if(null!=pushTexts&&pushTexts.size()>0){
            //把所有的消息，合并成一个消息
            AcceptPush acceptPush = PushMessageFactory.instancePushBucketWithoutId(receiver,pushTexts);
            messageMapper.savePushMessage(acceptPush);
            return Collections.singletonList(acceptPush);
        }
        return pushTexts;
    }

    public void setMessageMapper(MessageMapper messageMapper) {
        this.messageMapper = messageMapper;
    }
}
